<template>
  <div class="log-page">
    <!-- 搜索条件区域 -->
    <div class="search-section">
      <!-- 所有非时间、非描述、非按钮的搜索条件都放在这一行 -->
      <el-row :gutter="15" class="search-row">
        <el-col :span="2">
          <el-input
            v-model="searchForm.psName"
            placeholder="漆站"
            clearable
            size="medium"
          />
        </el-col>
        <el-col :span="2">
          <el-input
            v-model="searchForm.mlName"
            placeholder="主线"
            clearable
            size="medium"
          />
        </el-col>
        <el-col :span="2">
          <el-input
            v-model="searchForm.slName"
            placeholder="分配站"
            clearable
            size="medium"
          />
        </el-col>
        <el-col :span="2">
          <el-input
            v-model="searchForm.deviceName"
            placeholder="设备名称"
            clearable
            size="medium"
          />
        </el-col>
        <el-col :span="2">
          <el-input
            v-model="searchForm.colorCode"
            placeholder="颜色代码"
            clearable
            size="medium"
          />
        </el-col>
        <el-col :span="2">
          <el-input
            v-model="searchForm.roleName"
            placeholder="角色名称"
            clearable
            size="medium"
          />
        </el-col>
        <!-- <el-col :span="2">
          <el-input
            v-model="searchForm.roleLevel"
            placeholder="角色级别"
            clearable
            size="medium"
          />
        </el-col> -->

        <el-col :span="2">
          <el-input
            v-model="searchForm.oldEvent"
            placeholder="旧事件"
            clearable
            size="medium"
          />
        </el-col>
        <el-col :span="2">
          <el-input
            v-model="searchForm.newEvent"
            placeholder="新事件"
            clearable
            size="medium"
          />
        </el-col>
        <el-col :span="8">
          <el-input
            v-model="searchForm.description"
            placeholder="描述"
            clearable
            size="medium"
          />
        </el-col>
      </el-row>
      
      <el-row :gutter="15" class="search-row">
        <el-col :span="12">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="medium"
            class="w-full"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-col>
        <el-col :span="12" class="button-group">
          <el-button
            type="primary"
            @click="searchLogs"
            size="medium"
            style="width: 100px;"
          >
            查询
          </el-button>
          <el-button
            @click="resetSearch"
            size="medium"
            style="width: 100px;"
          >
            重置
          </el-button>
          <el-button
            type="success"
            @click="exportLogs"
            size="medium"
            style="width: 100px;"
          >
            导出CSV
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格显示区域 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="logData"
        border
        stripe
        style="width: 100%"
        size="medium"
      >
        <el-table-column prop="PSName" label="漆站"/>
        <el-table-column prop="MLName" label="主线" />
        <el-table-column prop="SLName" label="分配站" />
        <el-table-column prop="DeviceName" label="设备名称" />
        <el-table-column prop="ColorCode" label="颜色代码" />
        <el-table-column prop="RoleName" label="用户名称" />
        <!-- <el-table-column prop="RoleLevel" label="用户级别" /> -->
        <el-table-column prop="OldEvent" label="旧事件">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.OldEvent && scope.row.OldEvent.includes('打开')" 
              type="success"
              size="large"
            >
              {{ scope.row.OldEvent }}
            </el-tag>
            <el-tag 
              v-else-if="scope.row.OldEvent && scope.row.OldEvent.includes('关闭')" 
              type="info"
              size="large"
            >
              {{ scope.row.OldEvent }}
            </el-tag>
            <span v-else>{{ scope.row.OldEvent }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="NewEvent" label="新事件">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.NewEvent && scope.row.NewEvent.includes('打开')" 
              type="success"
              size="large"
            >
              {{ scope.row.NewEvent }}
            </el-tag>
            <el-tag
              v-else-if="scope.row.NewEvent && scope.row.NewEvent.includes('关闭')" 
              type="info"
              size="large"
            >
              {{ scope.row.NewEvent }}
            </el-tag>
            <span v-else>{{ scope.row.NewEvent }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="SystemLevel" label="系统液位 [L]" />
        <el-table-column prop="Description" label="描述" min-width="200">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.Description && scope.row.Description.includes('时间程序')"
              size="large"
            >
              {{ scope.row.Description }}
            </el-tag>
            <span v-else>{{ scope.row.Description }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="LogDateTime" label="时间" width="140" />
      </el-table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        size="medium"
      />
    </div>
  </div>
</template>

<script>


export default {
  name: 'LogPage',
  data() {
    return {
      searchForm: {
        psName: '',
        mlName: '',
        slName: '',
        deviceName: '',
        colorCode: '',
        roleName: '',
        roleLevel: '',
        oldEvent: '',
        newEvent: '',
        systemLevel: '',
        description: '',
        dateRange: []
      },
      logData: [],
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      loading: false
    };
  },
    mounted() {
      // 初始化搜索表单，设置默认选择当天
      this.resetSearch();
    },
    methods: {
      // 获取当天日期范围
      getTodayDateRange() {
        const today = new Date();
        const startDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
        const endDate = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);
        
        // 格式化为 YYYY-MM-DD HH:mm:ss
        const formatDate = (date) => {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        };
        
        return [formatDate(startDate), formatDate(endDate)];
      },
      
      resetSearch() {
        // 设置默认选择当天
        const todayRange = this.getTodayDateRange();
        
        this.searchForm = {
          psName: '',
          mlName: '',
          slName: '',
          deviceName: '',
          colorCode: '',
          roleName: '',
          roleLevel: '',
          oldEvent: '',
          newEvent: '',
          systemLevel: '',
          description: '',
          dateRange: todayRange
        };
        this.pagination.page = 1;
        this.searchLogs();
      },
      async searchLogs() {
        this.loading = true;
        try {
          const { psName, mlName, slName, deviceName, colorCode, roleName, roleLevel, oldEvent, newEvent, systemLevel, description, dateRange } = this.searchForm;
          const [startDate, endDate] = dateRange || [];
          
          // 调用后端API获取数据
          const response = await this.$axios.post('/logs', {
            psName,
            mlName,
            slName,
            deviceName,
            colorCode,
            roleName,
            roleLevel,
            oldEvent,
            newEvent,
            systemLevel,
            description,
            startDate,
            endDate,
            page: this.pagination.page,
            pageSize: this.pagination.pageSize
          });
          
          this.logData = response.data.data;
          this.pagination.total = response.data.total;
          console.log(this.logData);
        } catch (error) {
          console.error('查询日志失败:', error);
          this.$message.error('查询日志失败，请稍后重试');
        } finally {
          this.loading = false;
        }
      },
       
      async exportLogs() {
        this.loading = true;
        try {
          const { 
            psName, mlName, slName, deviceName, colorCode, roleName, roleLevel, 
            oldEvent, newEvent, systemLevel, description, dateRange 
          } = this.searchForm;
          const [startDate, endDate] = dateRange || [];
          
          // 调用后端API导出
          this.$message.info('正在导出数据，请稍候...');
          
          // 使用axios调用后端API导出
          const response = await this.$axios.post('/logs/export', {
            psName,
            mlName,
            slName,
            deviceName,
            colorCode,
            roleName,
            roleLevel,
            oldEvent,
            newEvent,
            systemLevel,
            description,
            startDate,
            endDate
          }, { responseType: 'blob' });
          
          // 处理导出的文件
          const blob = new Blob([response.data], { type: 'text/csv;charset=utf-8;' });
          const link = document.createElement('a');
          const url = URL.createObjectURL(blob);
          
          link.setAttribute('href', url);
          link.setAttribute('download', `日志数据_${new Date().toLocaleString('zh-CN').replace(/[/:, ]/g, '-')}.csv`);
          link.style.visibility = 'hidden';
          
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(url);
          
          // 设置定时器，避免用户过快点击
          setTimeout(() => {
            this.$message.success('导出请求已发送，请等待下载');
            this.loading = false;
          }, 1000);
        } catch (error) {
          console.error('导出日志失败:', error);
          this.$message.error('导出日志失败，请稍后重试');
          this.loading = false;
        }
      },
      
      // 前端CSV导出方法
      exportToCSV(data) {
        if (!data || data.length === 0) {
          this.$message.warning('没有数据可导出');
          return;
        }
        
        // 定义CSV表头
        const headers = [
          '漆站', '主线', '分配站', '设备名称', '颜色代码', '角色名称',
          '角色级别', '旧事件', '新事件', '系统级别', '描述', '时间'
        ];

        // 定义CSV数据行
        const rows = data.map(item => [
          item.psName || '',
          item.mlName || '',
          item.slName || '',
          item.deviceName || '',
          item.colorCode || '',
          item.roleName || '',
          item.roleLevel || '',
          item.oldEvent || '',
          item.newEvent || '',
          item.systemLevel || '',
          this.escapeCSV(item.description || ''),
          item.DateTime || ''
        ]);
        
        // 组合CSV内容
        const csvContent = [
          headers.join(','), // 表头
          ...rows.map(row => row.join(',')) // 数据行
        ].join('\n');
        
        // 创建并下载文件
        const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
        const link = document.createElement('a');
        const url = URL.createObjectURL(blob);
        
        link.setAttribute('href', url);
        link.setAttribute('download', `日志数据_${new Date().toLocaleString('zh-CN').replace(/[/:, ]/g, '-')}.csv`);
        link.style.visibility = 'hidden';
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      },
      
      // CSV转义处理 - 兼容IE浏览器
      escapeCSV(str) {
        if (str.indexOf(',') !== -1 || str.indexOf('"') !== -1 || str.indexOf('\n') !== -1) {
          // 替换双引号为两个双引号，然后用双引号包裹整个字符串
          return '"' + str.replace(/"/g, '""') + '"';
        }
        return str;
      },
      
      addFormField(form, name, value) {
        if (value !== undefined && value !== null && value !== '') {
          const field = document.createElement('input');
          field.type = 'hidden';
          field.name = name;
          field.value = value;
          form.appendChild(field);
        }
      },
      
      handleSizeChange(pageSize) {
        this.pagination.pageSize = pageSize;
        this.pagination.page = 1;
        this.searchLogs();
      },
      
      handleCurrentChange(page) {
        this.pagination.page = page;
        this.searchLogs();
      }
    }
  }
</script>

<style scoped>
.log-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-section {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-row {
  margin-bottom: 15px;
}

.search-row:last-child {
  margin-bottom: 0;
}

.button-group {
  display: flex;
  justify-content: flex-end;
}

.table-section {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  /* background-color: white; */
  /* padding: 20px; */
  /* border-radius: 8px; */
  /* box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); */
  display: flex;
  justify-content: flex-end;
}
</style>